package com.otdemo.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * DBUtil位于com.otdemo.util包下
 * com.otdemo.util这个包里，都是工具类
 * 因为util是英文单词utility的前四个字母
 *
 * @author LEI
 * DBUtil, 是针对数据库操作的工具类
 * 里面包含数据库的连接字符串，打开/关闭数据库，加载数据库驱动的操作
 */
public class DBUtil {
    public final static String URL = "jdbc:mysql://127.0.0.1:3306/dev?serverTimezone=GMT%2B8&characterEncoding=UTF-8";
    public final static String UID = "root";
    public final static String PWD = "123456";
    public final static String DRIVER = "com.mysql.cj.jdbc.Driver";

    public Connection con;
    public PreparedStatement ps;
    public ResultSet rs;

    public void open_db() throws SQLException {
        con = DriverManager.getConnection(URL, UID, PWD);
    }

    public void close_db() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
